<template>
  <div class="base-file-item">
    <template v-if="size === 'normal'">
      <div :class="clazz" :style="styl" @click.prevent.stop="handlePreviewFile(file)">
        <!-- <el-image v-if="isImage" :src="file.url" :alt="file.filename"></el-image> -->
      </div>
      <div class="base-file-info">
        <!-- <a :href="genDownloadUrl(file)">{{ file.filename }}</a> -->
        <div class="base-file-info-name cur-point one-ellipsis" @click="handlePreviewFile(file)">{{ file.filename }}</div>
        <p>
          <span>{{file.fileSize}}</span>
          <el-button type="button" class="btn-text base-file-del" @click="deleteFile" v-if="!readonly">{{$t('common.base.delete')}}</el-button>
        </p>
      </div>
      
      <!-- S 智能质检 -->
      <template v-if="isShowFileToIntelligent(file.filename) && file.sim != null">
        <div v-if="file.pass" class="base-file-intelligent-tips base-file-intelligent-success">{{$t('common.form.preview.file.qualitySuccess', {data1:file.sim})}}</div>
        <div v-else class="base-file-intelligent-tips">{{$t('common.form.preview.file.qualityError', {data1:file.sim})}}</div>
      </template>
      <!-- E 智能质检 -->
    </template>
    
    <!-- 用于添加备注 -->
    <template v-else>
      <div :class="clazz" :style="styl" @click.prevent.stop="handlePreviewFile(file)">
        <!-- <el-image v-if="isImage" :src="file.url" :alt="file.filename"></el-image> -->
      </div>
      <div class="base-file-info">
        <!-- <a :href="genDownloadUrl(file)">{{file.filename}}</a> -->
        <div class="base-file-info-name cur-point" @click="handlePreviewFile(file)">{{ file.filename }}</div>
        <el-button type="button" class="btn-text base-file-del" @click="deleteFile" v-if="!readonly">
          <i class="iconfont icon-circle-delete" style="position: relative;top: 1px"></i>
        </el-button>
      </div>
    </template>

    <biz-file-preview ref="bizPreviewFileDialog" :file="previewFile"></biz-file-preview>
  </div>
</template>

<script>
// TODO: 识别更多类型的文件
import platform from '@src/platform/index';
import { getOssUrl } from '@src/util/assets'
import { deleteServerFiles } from 'pub-bbx-utils';

export default {
  name: 'base-file-item',
  props: {
    file: {
      type: Object,
      default: () => ({})
    },
    /** 是否只读，如果为true，不允许删除操作 */
    readonly: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'normal',
    },
    Source:{
      type: Array,
      default: () =>[]
    },
    intelligentCheckNow: {
      type: Boolean,
      default: false
    },
    // 表单操作模式
    formEditingMode: {
      type: String,
      default: '', // create | edit
    },
    // 是否允许下载 
    fileDownloadAuth: {
      type: Boolean,
      default: true
    },
  },
  computed:{
    icon(){
      let file = this.file;
      let icon = '';
      const name = file.filename || file.url;
      
      if (/\.(png|bmp|gif|jpg|jpeg|tiff|image)$/i.test(name)) {
        icon = 'img';
      } else if (/\.(ppt|pptx)$/i.test(name)) {
        icon = 'ppt-file-icon';
      } else if (/\.(mp3)$/i.test(name)) {
        icon = 'voice-file-icon';
      } else if (/\.(mp4)$/i.test(name)) {
        icon = 'video-file-icon';
      } else if (/\.(zip)$/i.test(name)) {
        icon = 'zip-file-icon';
      } else if (/\.(pdf)$/i.test(name)) {
        icon = 'pdf-file-icon';
      } else if (/\.(xls|xlsx)$/i.test(name)) {
        icon = 'xls-file-icon';
      } else if (/\.(doc|docx)$/i.test(name)) {
        icon = 'doc-file-icon';
      } else if (/\.(txt)$/i.test(name)) {
        icon = 'txt-file-icon';
      } else if (/\.(csv)$/i.test(name)) {
        icon = 'csv-file-icon';
      } else {
        icon = 'other-file-icon';
      }
      
      if (this.size === 'small') {
        icon = `small-${icon}`;
      }
      
      return icon;
    },
    clazz(){
      let clazz = ['base-file-preview'];
      
      if(!this.isImage){
        clazz = clazz.concat(['base-file-icon', this.icon])
      }
      
      if (this.size === 'small') {
        clazz.push('small-base-file-preview')
        if(!this.isImage){
          clazz.push('small-base-file-icon')
        }
      }
      
      if (this.isOriginImage) {
        clazz.push('base-file-preview-origin')
      }
      
      return clazz;
    },
    styl(){
      let styl = {
        backgroundImage: `url(${getOssUrl('/file-icon.png')})`
      };
      
      if(this.isImage) {
        
        let suffix = this.file.url.indexOf('http') == 0 ? 'x-oss-process=image/resize,m_lfit,h_88,w_88' : 'isCmp=true';
        
        let url = `${this.file.url}${this.file.url.indexOf('?') >= 0 ? '&' : '?'}${suffix}`;

        if (this.isOriginImage) {
          url = this.file.url;
        }
        
        styl.backgroundImage = `url(${url})`;
        styl.cursor = 'pointer';
      }
      
      return styl;
    },
    // 是否为图片
    isImage(){
      return this.icon === 'img' || this.icon === 'small-img';
    },
    isOriginImage() {
      return this.file.url.indexOf('/files/auth/getSmsAptitude') > -1
    }
  },
  data() {
    return { 
      previewFile: {},
      previewFileType: ''
    }
  },
  methods: {
    // 预览文件
    handlePreviewFile(file) {
      const { fileSize, filename, id, url } = file
      const downloadUrl = this.genDownloadUrl(file)
      this.previewFile = {
        id,
        url,
        fileSize,
        fileName: filename,
        name: filename,
        downloadUrl,
        fileType: '',
        fileDownloadAuth: this.fileDownloadAuth
      }
      switch (this.icon) {
        case 'img':
        case 'small-img':
          this.previewFile.fileType = 'image'
          break;
        case 'pdf-file-icon':
        case 'small-pdf-file-icon':
          this.previewFile.fileType = 'pdf'
          break;
        case 'voice-file-icon':
        case 'small-voice-file-icon':
          this.previewFile.fileType = 'audio'
          break;
        case 'video-file-icon':
        case 'small-video-file-icon':
          this.previewFile.fileType = 'video'
          break;
        case 'doc-file-icon':
        case 'small-doc-file-icon':
          this.previewFile.fileType = 'word'
          break;
        case 'xls-file-icon':
        case 'small-xls-file-icon':
          this.previewFile.fileType = 'excel'
          break;
        case 'txt-file-icon':
        case 'small-txt-file-icon':
          this.previewFile.fileType = 'txt'
          break;
        case 'csv-file-icon':
        case 'small-csv-file-icon':
          this.previewFile.fileType = 'csv'
          break;
        case 'ppt-file-icon':
        case 'small-ppt-file-icon':
          this.previewFile.fileType = 'ppt'
          break;
        default:
          this.previewFile.fileType = ''
          break;
      }
      switch (this.previewFile.fileType) {
        //视频查看
        case "video": {
          this.$previewVideo(this.previewFile.url, this.previewFile);
          break;
        }

        //图片查看
        case "image": {
          this.$previewElementImg(this.previewFile.url, this.Source.filter(item=>/\.(png|bmp|gif|jpg|jpeg|tiff|image)$/i.test(item.url || item)), this.previewFile);
          break;
        }

        // PDF查看
        case "pdf": {
          this.$previewPDF(this.previewFile.url, this.previewFile);
          break;
        }

        // csv,txt, word, excel查看
        case "csv":
        case "txt":
        case "word":
        case "excel":
        case "ppt":
          const suffix = filename.substring(filename.lastIndexOf(".")+1)
          this.$previewFile({...this.previewFile, suffix});
          break;

        default:{
          if(!this.fileDownloadAuth) return
          let a = document.createElement('a');
          a.href = `/files/download?fileId=${this.previewFile.id}`;
          a.download = this.previewFile.fileName;
          a.click();
          window.URL.revokeObjectURL(a);
        }
      }
      
      // this.$refs.bizPreviewFileDialog.open()
    },

    genDownloadUrl(file){
      const {id,fileId} = file
      return `/files/download?fileId=${fileId || id}`;
    },
    preview(event){
      let element = event.target.querySelector('img');
      if(!this.isImage || !element) return;
      
      let list = event.target.closest('.base-file__preview');
      let images = Array.prototype.slice.call(list.querySelectorAll('img'));
      
      let currIndex = 0;
      let urls = images.map((item, index) => {
        if(item == element) currIndex = index;
        return item?.dataset?.origin || item.src;
      });
      
      platform.imagePreview({
        imageDom: list,
        currIndex,
        urls
      });
      
    },
    async deleteFile(){
      try {
        const name = this.file.filename || '';
        if(await platform.confirm(`${this.$t('common.form.preview.file.deleteFileTips')}\n${name}`)){
          this.$emit('delete', this.file);
          this.serverDeleteFile(this.file)
        }
      } catch (error) {
        console.error('error', error);
      }
    },
    serverDeleteFile(){
      const { formEditingMode } = this
      if (!this.formEditingMode) return;
      
      if (formEditingMode == 'create') {
        deleteServerFiles([this.file.id])
      } else if (formEditingMode == 'edit') {
        this.$emit('getDeleteFiles', [this.file.id]);
      }
    },
    // 显示指定的智能质检图片
    isShowFileToIntelligent(fileName) {
      return /\.(jpeg|jpg|png|bmp)$/i.test(fileName)
    },
  }
}
</script>

<style lang="scss">
.base-file-item{
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  margin-bottom: 4px;
  
  &:hover {
    .base-file-del{
      visibility: visible;
    }
  }
}

.base-file-info {
  flex: 1;
  overflow: hidden;
  margin-left: 10px;
  @include text-ellipsis;
  line-height: 1;
  position: relative;
  
  & > p {
    margin: 0;
    padding: 0;
    line-height: 18px !important;
    color: $text-color-secondary;
    font-size: 12px;
  }
  
  & > .base-file-info-name {
    color: $text-color-primary;
    line-height: 20px !important;;
    font-size: 14px;
    display: inline-block;
    vertical-align: middle;
    white-space: pre-wrap;
    &:hover{
      @include fontColor();
    }
  }
  .one-ellipsis{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width:100%;
  }
}

// 质检结果
.base-file-intelligent-tips{
  width: 120px;
  border-radius: 15px;
  margin-left: 8px;
  text-align: center;
  background: #FF7043;
  color: #FFFFFF;
  padding: 3px;
  font-size: 12px;
}
.base-file-intelligent-success{
  background: #52AE5C;
}

.base-file-preview{
  width: 38px;
  height: 38px;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0 2px rgba(0,0,0,.125);
  
  // img{
  //   display: none;
  // }
}

.small-base-file-preview {
  width: 20px;
  height: 20px;

}

.base-file-icon{
  background-size: 38px;
}

.small-base-file-icon{
  background-size: 20px;
}

.ppt-file-icon {
  background-position: left 0 top 0;
}
.voice-file-icon {
  background-position: left 0 top -38px;
}
.other-file-icon {
  background-position: left 0 top -76px;
}
.video-file-icon {
  background-position: left 0 top -114px;
}
.zip-file-icon {
  background-position: left 0 top -152px;
}
.pdf-file-icon {
  background-position: left 0 top -190px;
}
.xls-file-icon {
  background-position: left 0 top -228px;
}
.doc-file-icon {
  background-position: left 0 bottom -38px;
}
.txt-file-icon {
  background-position: left 0 bottom 0px;
}

// small
.small-ppt-file-icon {
  background-position: left 0 top 0;
}
.small-voice-file-icon {
  background-position: left 0 top -20px;
}
.small-other-file-icon {
  background-position: left 0 top -40px;
}
.small-video-file-icon {
  background-position: left 0 top -60px;
}
.small-zip-file-icon {
  background-position: left 0 top -80px;
}
.small-pdf-file-icon {
  background-position: left 0 top -100px;
}
.small-xls-file-icon {
  background-position: left 0 top -120px;
}
.small-doc-file-icon {
  background-position: left 0 bottom -20px;
}
.small-txt-file-icon {
  background-position: left 0 bottom 0px;
}

.base-file-del{
  margin-left: 5px;
  padding: 0;
  visibility: hidden;
  color: #9a9a9a;
  vertical-align: middle;
  // position: absolute;
  // right: -10px;
  
  &:hover{
    color: #ed3f14;
    .iconfont {
      color: #ed3f14;
    }
  }
}
.base-file-preview-origin {
  background-size: contain;
}
</style>